{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4f0243be",
   "metadata": {},
   "source": [
    "# Numpy\n",
    "\n",
    "NumPy是Python中科学计算的基本软件包。它是一个Python库，提供多维数组对象、各种派生类(如掩码数组和矩阵)和各种例程，用于对数组进行快速操作，包括数学、逻辑、形状操作、排序、选择、I/O、离散傅立叶变换、基本线性代数、基本统计操作、随机模拟等等。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "09c0574f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这一行的作用会在后面回答\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "472ea72e",
   "metadata": {},
   "source": [
    "**在使用之前首先要导入numpy模块**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "87b6720a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "637bf230",
   "metadata": {},
   "source": [
    "## 1.创建numpy数组\n",
    "\n",
    "有很多种方法去初始化新的numpy数组, 例如从\n",
    "\n",
    "* Python列表或元组\n",
    "* 使用专门用来创建numpy arrays的函数，例如 arange, linspace等\n",
    "* 从文件中读取数据"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3ff5435",
   "metadata": {},
   "source": [
    "### 1.1 从列表中创建\n",
    "\n",
    "从列表中创建新的向量或者矩阵，可以使用array函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "29092e47",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4] <class 'numpy.ndarray'>\n",
      "(4,)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3, 4])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "a=[1,2,3,4]\n",
    "v=np.array(a)\n",
    "print(v,type(v))#ndarray表示n维数组\n",
    "\n",
    "print(v.shape)#v的形状\n",
    "\n",
    "v  #直观表示"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfc2abad",
   "metadata": {},
   "source": [
    "嵌套列表的array函数可以得到矩阵，**矩阵的shape可以理解为每一层所包含的元素个数，**其实在二维的时候可以理解为行和列，但是一旦变成多维理解上就会出现困难。\n",
    "\n",
    "**矩阵的类型也是ndarray**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "792040fe",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1  2  3 10]\n",
      " [ 4  5  6 11]\n",
      " [ 7  8  9 12]]\n",
      "(3, 4)\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "matrix=np.array([[1,2,3,10],[4,5,6,11],[7,8,9,12]])#注意中括号\n",
    "\n",
    "print(matrix)\n",
    "print(matrix.shape)#第一层有三个，第二层有四个，三行四列\n",
    "print(type(matrix))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1f30e4d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 1  2]\n",
      "  [ 3  4]\n",
      "  [ 5  6]]\n",
      "\n",
      " [[ 3  4]\n",
      "  [ 5  6]\n",
      "  [ 7  8]]\n",
      "\n",
      " [[ 5  6]\n",
      "  [ 7  8]\n",
      "  [ 9 10]]\n",
      "\n",
      " [[ 7  8]\n",
      "  [ 9 10]\n",
      "  [11 12]]]\n",
      "\n",
      "(4, 3, 2)\n",
      "24\n"
     ]
    }
   ],
   "source": [
    "#继续创建一个三维的\n",
    "matrix = np.array([[[1,2], [3,4], [5,6]], \\\n",
    "              [[3,4], [5,6], [7,8]], \\\n",
    "              [[5,6], [7,8], [9,10]], \\\n",
    "              [[7,8], [9,10], [11,12]]])\n",
    "print(matrix)\n",
    "print()\n",
    "print(matrix.shape)#shape输出矩阵的规模\n",
    "print(matrix.size)#size输出元素的个数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec923e91",
   "metadata": {},
   "source": [
    "创建三维会自动输出下面的格式，但是为了不出错尽量不要在一行内写下所有的三维矩阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "15bec240",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 1,  2],\n",
       "        [ 3, 10]],\n",
       "\n",
       "       [[ 4,  5],\n",
       "        [ 6, 11]],\n",
       "\n",
       "       [[ 7,  8],\n",
       "        [ 9, 12]]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix=np.array([[[1,2],[3,10]],[[4,5],[6,11]],[[7,8],[9,12]]])\n",
    "matrix"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af7a70a2",
   "metadata": {},
   "source": [
    "之所以使用numpy.ndarray计算，而不使用列表，主要有以下原因：\n",
    "\n",
    "* 列表元素对应的数据类型很多，是动态的，不支持一些数学函数，实现数值计算效率并不高\n",
    "* numpy的数组是静态类型、同构的，且内存高校，可以做到快速实现数学函数\n",
    "\n",
    "**使用dtype函数就可以看出来他的数据类型，也可以人工改变数据类型（比如改成复数）**\n",
    "\n",
    "*常用类型有int, float, complex, bool（布尔 0false 非0true）, object*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a1634c18",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('int64')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "1f1cba9d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 1.+4.j,  2.+0.j],\n",
       "        [ 3.+0.j, 10.+0.j]]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix=np.array([[[1+4j,2],[3,10]]],dtype=complex)\n",
    "matrix"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89c70e5c",
   "metadata": {},
   "source": [
    "### 1.2 使用 数组生成函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "379644d6",
   "metadata": {},
   "source": [
    "0矩阵、1矩阵和对角阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "15d48330",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 0.]\n",
      " [0. 0.]]\n",
      "[[1. 1.]\n",
      " [1. 1.]]\n",
      "[[1 0 0 0]\n",
      " [0 2 0 0]\n",
      " [0 0 3 0]\n",
      " [0 0 0 4]]\n",
      "[[0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0]\n",
      " [1 0 0 0 0 0]\n",
      " [0 5 0 0 0 0]\n",
      " [0 0 6 0 0 0]\n",
      " [0 0 0 9 0 0]]\n"
     ]
    }
   ],
   "source": [
    "print(np.zeros((2,2)))\n",
    "print(np.ones((2,2)))\n",
    "print(np.diag([i for i in range(1,5)]))\n",
    "print(np.diag([1,5,6,9],k=-2))#和主对角线有偏离"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee56f29e",
   "metadata": {},
   "source": [
    "**arange函数**（注意只有一个r不是arrange）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "812451be",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "[-1.00000000e+00 -9.00000000e-01 -8.00000000e-01 -7.00000000e-01\n",
      " -6.00000000e-01 -5.00000000e-01 -4.00000000e-01 -3.00000000e-01\n",
      " -2.00000000e-01 -1.00000000e-01 -2.22044605e-16  1.00000000e-01\n",
      "  2.00000000e-01  3.00000000e-01  4.00000000e-01  5.00000000e-01\n",
      "  6.00000000e-01  7.00000000e-01  8.00000000e-01  9.00000000e-01]\n"
     ]
    }
   ],
   "source": [
    "x=np.arange(10)\n",
    "print(x)\n",
    "y=np.arange(-1,1,0.1)#依旧不包含尾端点\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f030bbe",
   "metadata": {},
   "source": [
    "**linspace（等差、包含尾端点） and logspace（等比）**\n",
    "\n",
    "np.logspace(start=开始值，stop=结束值，num=元素个数，base=指定对数的底, endpoint=是否包含结束值)\n",
    "\n",
    "开始和结束值表示的是指数，而非对应的数值，默认base=10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "4744a53f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1.,  2.,  4.,  8., 16., 32.])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.logspace(0,5,6,base=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fd5f835",
   "metadata": {},
   "source": [
    "**mgrid**  (np.mgrid[start,end,step])\n",
    "\n",
    "如果step后面加了j表示n步，否则表示一步增加n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "076f73e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[-5., -5., -5.],\n",
       "        [ 0.,  0.,  0.],\n",
       "        [ 5.,  5.,  5.]]),\n",
       " array([[-2.,  0.,  2.],\n",
       "        [-2.,  0.,  2.],\n",
       "        [-2.,  0.,  2.]]))"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#x是按照列，也就是第一维度增加的，而y则是按照第二维度也就是按行增加的\n",
    "#这样就可以按行、按列先对矩阵进行扩展，然后相加得到一些复杂的矩阵\n",
    "x,y=np.mgrid[-5:5:3j,-2:2:3j]\n",
    "x,y"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2500db3",
   "metadata": {},
   "source": [
    "**random data**    [random下有很多不同的函数](https://blog.csdn.net/weixin_42029738/article/details/81977492),这里主要介绍两个"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a29b75db",
   "metadata": {},
   "source": [
    "random.rand随机数均匀地分布在[0,1)区间内"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "46a61e1a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[0.01154487, 0.73611791, 0.22257861],\n",
       "        [0.27574929, 0.94299004, 0.18883483],\n",
       "        [0.11205575, 0.60070263, 0.27985867],\n",
       "        [0.57358486, 0.40160298, 0.35669652]],\n",
       "\n",
       "       [[0.92629443, 0.57701568, 0.73524346],\n",
       "        [0.25404957, 0.70946601, 0.87920434],\n",
       "        [0.38409549, 0.819799  , 0.78060397],\n",
       "        [0.44238053, 0.05500964, 0.97886949]]])"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from numpy import random\n",
    "random.rand(2,4,3)#size"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c2c356f",
   "metadata": {},
   "source": [
    "random.randn生成标准正态分布随机数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "69170fdb",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.17207192,  0.47392143, -0.70151797,  1.27373232],\n",
       "       [ 0.77679493,  1.02754924,  0.65252086,  0.83618743],\n",
       "       [ 0.80890863,  0.29825607,  1.1128433 ,  1.4487988 ],\n",
       "       [ 0.43287392,  2.01617374,  0.3935937 , -0.44943079],\n",
       "       [ 0.97278821,  0.34055456,  0.1883616 , -2.09069884]])"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "random.randn(5,4)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
